package clone;

import java.util.ArrayList;

// 深拷贝 / 浅拷贝
public class Test {
    public static void main(String[] args) {
        ShallowCopyTest shallow = new ShallowCopyTest();
        shallow.setValue("张三");

        ShallowCopyTest cloneShallow = shallow.clone();
        cloneShallow.setValue("李四");

        // 输出结果 ?
        System.out.println(shallow.getValue());

        DeepCopyTest deep = new DeepCopyTest();
        deep.setValue("张三");

        DeepCopyTest cloneDeep = deep.clone();
        cloneDeep.setValue("李四");

        // 输出结果 ?
        System.out.println(deep.getValue());
    }

}

class ShallowCopyTest implements Cloneable {

    private ArrayList<String> arrayList = new ArrayList<String>();

    @Override
    protected ShallowCopyTest clone()  {
        ShallowCopyTest shallow = null;
        try {
            shallow = (ShallowCopyTest) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return shallow;
    }

    public ArrayList<String> getValue() {

        return this.arrayList;
    }

    public void setValue(String value) {
        this.arrayList.add(value);
    }
}

class DeepCopyTest implements Cloneable {

    private ArrayList<String> arrayList = new ArrayList<String>();

    @Override
    protected DeepCopyTest clone()  {
        DeepCopyTest deep = null;
        try {
            deep = (DeepCopyTest) super.clone();

            // 修改为深拷贝
            deep.arrayList = (ArrayList<String>) this.arrayList.clone();

        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return deep;
    }

    public ArrayList<String> getValue() {

        return this.arrayList;
    }

    public void setValue(String value) {
        this.arrayList.add(value);
    }
}